/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package worker;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
//import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion.User;
import data.enumeration.SRSCity;
import data.sunriseset.Sun;
import java.io.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author bsmith
 */
public class SunRiseSetWorker {

    private static final SunRiseSetWorker sunRiseSetWorkerInstance = new SunRiseSetWorker();

    private SunRiseSetWorker() {
    }

    public static SunRiseSetWorker getInstance() {
        return sunRiseSetWorkerInstance;
    }

    /**
     *
     * @param sunRiseSetXMLFileName
     * @param city
     * @param year - Gregorian Years
     * @param month - 1 to 12
     * @param day - 1 to 31
     * @throws IOException
     */
    public void saveWebServiceFile(String sunRiseSetXMLFileName, SRSCity city, int year, int month, int day) throws IOException {
        Client client = Client.create();
        Float longitude = 0.0f;
        Float latitude = 0.0f;
        if (city == SRSCity.Canberra) {
            longitude = -35.3025f;
            latitude = 149.13333f;
        } else {
            throw new IllegalStateException("Unknown City for long/lat:" + city);
        }
        String resource = "http://www.earthtools.org/sun/" + longitude + "/" + latitude + "/" + day + "/" + month + "/99/0";
        //System.out.println("SunSS resource:"+resource);
        String s = null;
        Writer w = null;
        try {
            WebResource webResource = client.resource(resource);
            s = webResource.get(String.class);
        } catch (UniformInterfaceException ex) {
            throw new UniformInterfaceException("Error retrieving from webservice using '"+resource+"'",ex.getResponse());
        }
        File xmlFile = new File(sunRiseSetXMLFileName);
        w = new FileWriter(xmlFile);
        w.write(s);
    }

    public Sun buildObject(String sunRiseSetXMLFileName) throws JAXBException, FileNotFoundException {
        JAXBContext context = JAXBContext.newInstance(Sun.class); //1
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Sun sun = (Sun) unmarshaller.unmarshal(new FileReader(sunRiseSetXMLFileName)); //2
        return sun;
    }
}
